import 'dart:convert';
import 'dart:io';

import 'package:eshi/app/MyApp.dart';
import 'package:eshi/app/shi/taxis/tab_edit_page/tab_edit_page_event.dart';
import 'package:eshi/app/utils/ContentUriHandler.dart';
import 'package:eshi/app/utils/file_watcher.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:eshi/app/MyHomePage.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';
import 'package:eshi/app/shi/data/tabtxt_history.dart';
import 'package:eshi/app/shi/taxis.dart';
import 'package:eshi/app/shi/widget/WebTextWidget.dart';
import 'package:flutter/services.dart' show rootBundle, MethodChannel;
// import 'package:flutter_web_plugins/flutter_web_plugins.dart' ;


final GlobalKey<TimeAxisState> customWidgetKey = GlobalKey();
final GlobalKey<MyHomePageState> mainWidgetKey = GlobalKey();
void main() async{
  // if(kIsWeb){
  //   // 移除URL中的"#"号 (可选)
  //   setUrlStrategy(PathUrlStrategy());
  // }
  runApp(MyApp());
  onLoadingCompleted();
}

onLoadingCompleted() async{
  if(kIsWeb){
    await FileParser.initAssets();
  }
  WebTextWidget.initWebView();
  System.initValues();
  print("system init ok!");
  await Config.initSaveEngine();
  print("config init ok!");
  await Future.delayed(Duration(microseconds: 500));

  //手机端copy资源数据到手机 
  if(!kIsWeb && (Platform.isAndroid || Platform.isIOS) && !Config.initAssets){
      await FileParser.copyAssetToWritableDir();
      // Config.initAssets = true;
      print("init assets");   
  }
  await TabTxtHistory.initItems();
  print("file init ok!");
  
  androidEventHandler.init();
   print("init over!");
  // printAssetManifest();
  if( Platform.isLinux) {
    monitorFileChange();
  }
}
monitorFileChange([String name="颗粒的快乐生活"]){
  final watcher = FileWatcher(  checkInterval: const Duration(seconds: 3), // 每3秒检查一次
  );
   // 监听指定文件
  watcher.startWatching(
    filePath: 'assets/txt/$name.txt',
    onModified: () async{
      // 处理文件变化
      print("文件已修改");
      mainWidgetKey.currentState?.changeHistory(await TabTxtHistory.load(name,true));      
    },
    onError: (error) {
      print("监听错误: $error");
    },
  );
}
Future<void> printAssetManifest() async {
  final manifestContent = await rootBundle.loadString('AssetManifest.json');
  final Map<String, dynamic> manifestMap = json.decode(manifestContent);
  print('可用资源: $manifestMap');
}

class androidEventHandler {
    // 与原生侧一致的通道名称
    static const _methodChannel = AndroidChannel.platform;

    // 初始化事件监听
    static void init() {
        ContentUriHandler.channel = _methodChannel;
        // 监听原生侧发送的事件
        _methodChannel.setMethodCallHandler((call) async {
            // 根据方法名区分事件类型
            if (call.method == 'onFileOpened') {
                // 获取原生传递的文件URI
                final fileUri = call.arguments as String;
                print('Dart侧收到文件打开事件：$fileUri');
                // 处理文件（如解析URI、读取内容等）
                _handleFileUri(fileUri);
            }
        });
    }

    // 处理文件URI
    static void _handleFileUri(String uri) async {
        File? tempFile = await ContentUriHandler.saveContentUriToTempDir(uri);
        if(tempFile!=null)
        // 实现文件处理逻辑（如转换为文件路径、读取内容等）
        TabEditPageEvent.loadDtt(tempFile.path);
    }

    
}
